<template>
  <page-header-wrapper v-if="pathName == 'user-list'" :key="key">
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="名称">
                <a-input v-model="queryParam.name" placeholder="" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="账号">
                <a-input v-model="queryParam.account" placeholder="" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="最后登录IP">
                <a-input v-model="queryParam.ip" placeholder="" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <span
                class="table-page-search-submitButtons"
                :style="(advanced && { float: 'right', overflow: 'hidden' }) || {}"
              >
                <a-button type="primary" @click="handleSearch">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => (this.queryParam = {})">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <div class="table-operator">
        <!-- <a-button type="primary" icon="plus" v-action:user_add @click="handleAdd">新建</a-button> -->
        <a-button type="primary" icon="plus" @click="handleAdd">新建</a-button>
      </div>

      <s-table
        ref="table"
        size="default"
        rowKey="id"
        :columns="columns | columnsFilter"
        :data="loadData"
        showPagination="auto"
        :scroll="{ x: true }"
        :pagination="{ 'show-total': (total) => `Total ${total} items` }"
      >
        <span slot="action" slot-scope="text, record">
          <template>
            <span>
              <a @click="handleEdit(record)">编辑</a>
              <a-divider type="vertical" />
            </span>
            <span>
              <a @click="handleFreeze(record, record.status)">{{ record.status == 1 ? '冻结' : '解冻' }}</a>
              <a-divider type="vertical" />
            </span>
            <span>
              <a @click="handleDel(record)">删除</a>
            </span>
          </template>
        </span>
        <span slot="address" slot-scope="text, scope">
          <span>{{ `${scope.country || 'x'}-${scope.province || 'x'}-${scope.city || 'x'}` }}</span>
        </span>
        <span slot="headImg" slot-scope="text">
          <img v-if="text" :src="`${baseUrl}/${text}`" alt="" class="tableImg headImg" />
          <img
            v-else
            src="https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png"
            alt=""
            class="tableImg headImg"
          />
        </span>
        <span slot="status" slot-scope="text">
          <a-badge
            :color="text | statusFilter(userStatusList, 'status')"
            :text="text | statusFilter(userStatusList, 'name')"
          />
        </span>
        <span slot="type" slot-scope="text">
          <a-badge
            :color="text | statusFilter(userTypeList, 'status')"
            :text="text | statusFilter(userTypeList, 'name')"
          />
        </span>
        <span slot="sex" slot-scope="text">
          <a-badge v-if="text == 1" status="processing" text="男" />
          <a-badge v-else status="error" text="女" />
        </span>
      </s-table>
      <user-form
        ref="createModal"
        :visible="visible"
        :loading="confirmLoading"
        :model="mdl"
        :roleList="roleList"
        @cancel="handleCancel"
        @ok="handleOk"
      />
    </a-card>
  </page-header-wrapper>
  <!-- <page-header-wrapper v-else> -->
  <router-view :key="key" v-else></router-view>
  <!-- </page-header-wrapper> -->
</template>

<script>
import { STable, ColumnSwicth } from '@/components'
import { getUserList, userAdd, userUpdate } from '@/api/login'
import {
  roleByNoAuth,
} from '@/api/noAuth'
import { userStatusList, userTypeList } from '@/utils/other'
import { mapGetters } from 'vuex'
import UserForm from './modules/UserForm'
import { Cascader } from 'ant-design-vue'

const columns = [
  {
    title: '名称',
    dataIndex: 'name',
    key: 'name',
    width: 150,
    fixed: true,
  },
  {
    title: '账号',
    dataIndex: 'account',
    key: 'account',
    width: 150,
  },
  {
    title: '手机号码',
    dataIndex: 'phone',
    customRender: (text) => text || '--',
  },
  {
    title: '余额',
    dataIndex: "unitPrice",
    key: "unitPrice",
  },

  {
    title: '最后登录时间',
    dataIndex: 'lastLoginTime',
    sorter: true,
    check: false,
    customRender: (text) => text || '--',
  },
  {
    title: '最后登录Ip',
    dataIndex: 'lastLoginIp',
    check: false,
    customRender: (text) => text || '--',
  },
  {
    title: '添加人',
    dataIndex: 'addUserName',
    check: false,
    customRender: (text) => text || '--',
  },
  {
    title: '添加时间',
    dataIndex: 'addTime',
    check: false,
    customRender: (text) => text || '--',
  },
  {
    title: '最后编辑人',
    dataIndex: 'lastUpdateUserName',
    check: false,
    customRender: (text) => text || '--',
  },
  {
    title: '最后编辑时间',
    dataIndex: 'lastUpdateTime',
    check: false,
    customRender: (text) => text || '--',
  },
  {
    title: '状态',
    dataIndex: 'status',
    scopedSlots: { customRender: 'status' },
  },
  {
    title: '操作',
    dataIndex: 'action',
    // width: '240px',
    scopedSlots: { customRender: 'action' },
  },
]

const sexList = [
  {
    id: 1,
    status: 'success',
    name: '男',
  },
  {
    id: 2,
    status: 'error',
    name: '女',
  },
]

export default {
  name: 'AWM-userList',
  components: {
    STable,
    UserForm,
    ColumnSwicth,
    'a-cascader': Cascader,
  },
  data() {
    // this.columns = columns
    return {
      value: 1,
      projectTypeList: [],
      projectTypeList1: [],
      pathName: '',
      columns,
      timeout: null,
      inviteUserList: [],
      fetching: false,
      // create model
      visible: false,
      confirmLoading: false,
      mdl: null,
      CG: {
        visible: false,
        confirmLoading: false,
        mdl: null,
      },
      // 测试
      ceshi: {
        visible: false,
        confirmLoading: false,
        mdl: null,
      },
      work: {
        visible: false,
        userId: null,
      },
      structure: {
        visible: false,
        userId: null,
      },

      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      parameter: {
        pageNum: 1,
        pageSize: 10,
      },
      queryParam: {},
      levelList: [], //  等级
      roleList: [], // 权限列表
      studioList: [], //  工作室列表
      // 状态
      userStatusList,
      //  角色类型
      userTypeList,
      // 性别
      sexList,
      // 排序
      sortJ: {
        levelNum: 'us.level_num',
        lastLoginTime: 'last_login_time',
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        let sortJ = this.sortJ
        if (parameter.sortField) {
          parameter.sortJ = sortJ
        }
        const requestParameters = Object.assign({type: 1}, parameter, this.queryParam)
        return getUserList(requestParameters).then((res) => {
          let result = {
            data: res.data.data,
            pageNo: parameter.pageNo,
            pageSize: parameter.pageSize,
            totalCount: res.data.total,
            totalPage: res.data.pages,
          }
          return result
        })
      },
      table: {
        data: [],
        loading: false,
        // pagination:{pageSize: 10, current: 1},
        pagination: {},
        columns: [],
        filters: null,
        sorter: null,
        key: 0,
        current: 1,
      },
      selectedRowKeys: [],
      selectedRows: [],
      key: 0,
    }
  },
  filters: {
    columnsFilter: function (a) {
      if (a) {
        return a.filter((v) => v.check || v.check == undefined)
      } else {
        return []
      }
    },
  },
  created() {
    let name = this.$route.name
    this.getRoleList()
    if (name == 'user-list-workDetails') {
      this.pathName = name
    } else {
      this.pathName = 'user-list'
    }
  },
  computed: {
    ...mapGetters({ baseUrl: 'baseUrl' }),
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange,
      }
    },
  },
  methods: {
    handleSearch() {
      this.$refs.table.refresh(true)
    },
    getRoleList() {
      roleByNoAuth({ pageNum: 1, pageSize: 100 })
        .then((res) => {
          console.log(11111111,res.data.data)
          this.roleList = res.data.data
        })
        .catch((err) => {})
    },
    handleAdd() {
      this.mdl = null
      this.visible = true
    },
    handleEdit(record) {
      this.visible = true
      this.mdl = { ...record }
    },
    saveCB() {
      const form = this.$refs.createModal.form
      this.visible = false
      this.confirmLoading = false
      // 重置表单数据
      form.resetFields()
      // 刷新表格
      this.$refs.table.refresh()
    },
    handleOk() {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      console.log(111111)
      form.validateFields((errors, values) => {
        console.log(values,errors)
        values.type = 1
        if (!errors) {
          if (values.id > 0) {
            userUpdate(values)
              .then((res) => {
                this.saveCB()
                this.$message.success('修改成功!')
              })
              .catch((err) => {
                this.saveCB()
              })
          } else {
            delete values.id
            userAdd(values)
              .then((res) => {
                this.saveCB()
                this.$message.success('新增成功!')
              })
              .catch((err) => {
                this.saveCB()
              })
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel() {
      this.visible = false
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    handleDel(a_record) {
      let self = this
      const modal = self.$confirm({
        title: '用户删除',
        content: `是否删除用户:${a_record.name}`,
        okText: '确认',
        cancelText: '取消',
        onOk: () => self.handleDeleteRole(a_record.id, modal, -1),
        onCancel: () => {},
      })
    },
    handleFreeze(a_record, a_status) {
      let self = this
      const modal = self.$confirm({
        title: `用户${a_status == 1 ? '冻结' : '解冻'}`,
        content: `是否${a_status == 1 ? '冻结' : '解冻'}用户:${a_record.name}`,
        okText: '确认',
        cancelText: '取消',
        onOk: () => self.handleDeleteRole(a_record.id, modal, a_status == 1 ? 2 : 1),
        onCancel: () => {},
      })
    },
    handleDeleteRole(a_id, a_modal, a_type) {
      return new Promise((resolve, reject) => {
        let data = { id: a_id, status: a_type }
        userUpdate(data)
          .then((res) => {
            this.$refs.table.refresh()
            this.$message.success('删除成功!')
            resolve()
          })
          .catch((err) => {
            a_modal.destroy()
            this.$message.error('操作失败!')
          })
      })
    },
  },
  watch: {
    '$route.name': function (n, o) {
      this.pathName = n
      this.key++
    },
  },
}
</script>
<style scoped>
a {
}
</style>

 